<template>
  <h4>字段管理</h4>
  接口筛选：
  <el-select v-model="currentApiInfo" filterable size="small" style="margin-right: 20px" value-key="id"
             @change="filterByApi">
    <el-option :title="item.apiName"
               v-for="item in allApi"
               :key="item.id"
               :label="item.apiName + '(' + item.apiType + ' ' + item.apiUri + ')'"
               :value="item"/>
  </el-select>
  字段筛选：
  <el-input size="small" style="width: 200px; margin-right: 10px" v-model="filterFieldName" clearable
            placeholder="输入可根据字段名称或说明筛选" @change="filterByName" @blur="filterByName"
            @keyup.enter="filterByName"/>
  <el-switch v-model="isStrict" active-color="#13ce66" inactive-color="#ff4949"
             :active-value="true" :inactive-value="false" active-text="精准" inactive-text="模糊"
             style="margin-left: -6px;margin-right: 18px"/>

  <el-button circle size="small" title="增加字段" @click="addApiField">
    <el-icon>
      <Plus/>
    </el-icon>
  </el-button>

  <!-- 刷新 -->
  <el-button circle size="small" title="刷新数据" @click="findAllField">
    <el-icon>
      <Refresh/>
    </el-icon>
  </el-button>

  <div style="width: 1412px; margin: 10px auto">
    <el-row justify="center" align="middle">
      <el-col :span="10">
        <el-pagination :current-page="currentPage" :page-size="pageSize"
                       :page-sizes="[10, 20, 50, 100]" :small="true" :background="true"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="fieldsDisplay.length"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      </el-col>
    </el-row>
    <el-scrollbar height="76vh">
      <el-table :data="this.fieldsDisplay.slice((currentPage - 1) * pageSize, currentPage * pageSize)" border>
        <el-table-column fixed type="index" :label="tabFields[0].name" :width="tabFields[0].size"/>
        <el-table-column fixed :prop="tabFields[1].field" :label="tabFields[1].name" :width="tabFields[1].size"/>

        <!--  接口    -->
        <el-table-column :label="tabFields[7].name" :width="tabFields[7].size">
          <template #default="scope">
            <el-select v-model="scope.row[tabFields[7].field]" size="small" filterable
                       @change="updateFieldDo(scope.row)">
              <el-option :title="item.apiName"
                         v-for="item in allApi"
                         :key="item.id"
                         :label="item.apiName + '(' + item.apiType + ' ' + item.apiUri + ')'"
                         :value="item.id"/>
            </el-select>
          </template>
        </el-table-column>

        <!-- 字段数据类型 -->
        <el-table-column :label="tabFields[2].name" :width="tabFields[2].size">
          <template #default="scope">
            <el-select v-model="scope.row[tabFields[2].field]" size="small"
                       @change="updateFieldDo(scope.row)" value-key="enumValue">
              <el-option v-for="item in fieldTypeAll"
                         :key="item.enumValue"
                         :label="item.enumName"
                         :value="item.enumValue"/>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column :prop="tabFields[3].field" :label="tabFields[3].name" :width="tabFields[3].size"/>
        <el-table-column :prop="tabFields[4].field" :label="tabFields[4].name" :width="tabFields[4].size"
                         :show-overflow-tooltip="true"/>

        <!-- 停启用 -->
        <el-table-column :label="tabFields[8].name" :width="tabFields[8].size">
          <template #default="scope">
            <el-switch size="small" @change="updateFieldDo(scope.row)"
                       v-model="scope.row[tabFields[8].field]"
                       :active-value="1"
                       :inactive-value="0"
                       active-text="启"
                       inactive-text="停">
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column :prop="tabFields[5].field" :label="tabFields[5].name" :width="tabFields[5].size"
                         :show-overflow-tooltip="true"/>

        <el-table-column fixed="right" :label="tabFields[6].name" :width="tabFields[6].size">
          <template #default="scope">
            <el-button text type="primary" size="small" @click="updateApiField(scope.row)"
                       title="更多信息修改" class="icon-button">
              <el-icon>
                <Edit/>
              </el-icon>
            </el-button>
            <el-button text type="primary" size="small" @click="copyApiField(scope.row)"
                       title="参数说明复制" class="icon-button">
              <el-icon>
                <DocumentCopy/>
              </el-icon>
            </el-button>
            <el-button text type="danger" size="small" @click="deleteApiField(scope.row)"
                       title="参数删除" class="icon-button">
              <el-icon>
                <Delete/>
              </el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>
  </div>

  <!-- 接口目录编辑 -->
  <el-dialog
      :title="fieldTitle"
      v-model="fieldVisible"
      width="50%">
    <el-form ref="fieldMenuForm" :model="apiField" :rules="fieldRules" label-width="120px">
      <el-form-item label="字段名称" prop="fieldName">
        <el-input v-model="apiField.fieldName" show-word-limit title="字段"
                  :maxlength="200" type="text"></el-input>
      </el-form-item>

      <el-form-item label="通用字段说明" prop="fieldDesc">
        <el-input v-model="apiField.fieldDesc" show-word-limit title="字段说明"
                  maxlength="255" type="textarea"></el-input>
      </el-form-item>

      <el-form-item label="对应接口" prop="apiId">
        <el-select v-model="apiField.apiId" filterable size="small">
          <el-option :title="item.apiName"
                     v-for="item in allApi"
                     :key="item.id"
                     :label="item.apiName + '(' + item.apiType + ' ' + item.apiUri + ')'"
                     :value="item.id"/>
        </el-select>
      </el-form-item>

      <el-form-item label="字段类型" prop="fieldTypeId">
        <el-select v-model="apiField.fieldTypeId" size="small" value-key="enumValue">
          <el-option v-for="item in fieldTypeAll"
                     :key="item.enumValue"
                     :label="item.enumName"
                     :value="item.enumValue"/>
        </el-select>
      </el-form-item>

      <el-form-item label="字段优先级" prop="usePriority">
        <el-input v-model="apiField.usePriority" type="number" style="width: 200px" size="small"/>
      </el-form-item>

      <el-form-item label="是否必须" prop="fieldMust">
        <el-radio-group v-model="apiField.fieldMust" size="small">
          <el-radio-button label="是">是</el-radio-button>
          <el-radio-button label="否">否</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="是否启用" prop="enableFlag">
        <el-switch v-model="apiField.enableFlag"
                   :active-value="1"
                   :inactive-value="0"
                   active-text="启"
                   inactive-text="停">
        </el-switch>
      </el-form-item>

      <el-form-item label="修改时间">
        <el-date-picker disabled
                        size="small"
                        v-model="apiField.updateTime"
                        type="datetime"
                        placeholder="修改时间"/>
      </el-form-item>
    </el-form>
    <template #footer>
    <span class="dialog-footer">
      <el-button @click="fieldVisible = false">取 消</el-button>
      <el-button type="primary" @click="updateFieldOne()">确 定</el-button>
    </span>
    </template>
  </el-dialog>

</template>

<script>
import axios from "@/plugins/myaxios";
import myaxios from "@/plugins/myaxios";
import {ElMessage} from "element-plus";
import {DocumentCopy, Edit, Folder, Phone, Plus, Refresh, Delete} from '@element-plus/icons-vue'
import ApiDocManageConstants from "@/utils/api-utils/ApiDocManageConstants";
import CommonUtils from "@/utils/CommonUtils";
import ApiDocConstants from "@/utils/api-utils/ApiDocConstants";
import FormRules from "@/utils/FormRules";

export default {
  name: "ApiParamFieldManage",
  components: {Delete, Plus, Edit, Folder, Phone, DocumentCopy, Refresh},
  data() {
    return {
      allApi: [],
      allField: [],
      fieldsDisplay: [],
      currentApiInfo: ApiDocConstants.commonApiInfo,
      tabFields: ApiDocManageConstants.fieldTbObj,
      fieldTypeAll: [],
      fieldTitle: '',
      fieldVisible: false,
      apiField: {},
      fieldRules: {
        fieldName: FormRules.rules.fieldName,
        fieldDesc: FormRules.rules.fieldCommon,
        fieldTypeId: FormRules.rules.fieldType,
        fieldMust: FormRules.rules.must,
        apiId: FormRules.rules.apiId,
        enableFlag: FormRules.rules.enableFlag,
        usePriority: FormRules.rules.apiId
      },
      filterFieldName: '',
      isStrict: false,
      pageSize: 10,
      currentPage: 1,
      fieldsSize: 0
    }
  },
  methods: {
    findAllField() {
      let spaceId = this.$store.state.space.id ? this.$store.state.space.id : 1;
      axios.get(`/dist/field/findBySpaceId/${spaceId}`).then(rep => {
        // 将搜索结果赋值给接口列表
        if (rep.data.code !== 100) {
          ElMessage.error(rep.data.msg)
          return
        }
        if (rep.data.data) {
          this.allField = rep.data.data
          this.fieldsSize = this.allField.length
          this.fieldsDisplay = this.allField
        }
      }, err => {
        ElMessage.error('查询接口信息失败。')
      })
    },
    findAllApiInfo() {
      let spaceId = this.$store.state.space.id ? this.$store.state.space.id : 1;
      axios.get(`/dist/api/findAll/${spaceId}`).then(req => {
        // 将搜索结果赋值给接口列表
        if (req.data.code !== 100) {
          ElMessage.error(req.data.data.msg)
        }

        this.allApi = req.data.data
        this.allApi.unshift(ApiDocConstants.commonApiInfo)
      }, err => {
        ElMessage.error('查询接口信息失败。')
      })
    },
    filterByApi() {
      this.fieldsDisplay = this.allField.filter(field => field.apiId === this.currentApiInfo.id);
    },
    filterByName() {
      console.log(this.filterFieldName)
      if (!this.filterFieldName || this.filterFieldName === '') {
        return
      }
      if (this.isStrict) {
        this.fieldsDisplay = this.allField.filter(field => (field.fieldName === this.filterFieldName
            || field.fieldDesc === this.filterFieldName));
      } else {
        this.fieldsDisplay = this.allField.filter(field => (field.fieldName.indexOf(this.filterFieldName) > -1
            || field.fieldDesc.indexOf(this.filterFieldName) > -1));
      }
    },
    updateApiField(data) {
      this.apiField = data
      this.fieldVisible = true
      this.fieldTitle = "修改 " + data.fieldName + ' 字段信息'
    },
    copyApiField(data) {
      this.apiField = CommonUtils.cloneObj(data)
      this.apiField.id = null
      this.fieldVisible = true
      this.fieldTitle = "复制 " + data.fieldName + ' 字段信息'
    },
    deleteApiField(data) {
      this.$confirm(`确认删除《${data.fieldName}》字段，并删除所在参数说明？`, '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        myaxios.delete(`/dist/field/${data.id}`).then(rep => {
          // 处理res
          if (rep.data.code !== 100) {
            ElMessage.error(rep.data.msg);
            return;
          }
          // 删除对应目录
          this.allField.splice(this.allField.indexOf(data), 1)
          this.fieldsDisplay.splice(this.fieldsDisplay.indexOf(data), 1)
          ElMessage.success('删除目录成功。')
        }, err => {
          ElMessage.error('移动失败！')
        })
      })
    },
    addApiField() {
      let size = 0
      for (const field of this.tabFields) {
        size += field.size
      }
      console.log(size)
      this.apiField = ApiDocManageConstants.getFieldObj()
      this.fieldVisible = true
      this.fieldTitle = "修改字段信息"
    },
    // 在表中直接修改
    updateTb(data, field) {

    },
    updateFieldOne() {
      this.updateFieldDo(this.apiField);
    },
    updateFieldDo(data) {
      myaxios.put("/dist/field/upsertOne", data).then(rep => {
        // 处理res
        if (rep.data.code !== 100) {
          ElMessage.error(rep.data.msg);
          return;
        }
        ElMessage.success('修改成功。')
        this.fieldVisible = false;
      }, err => {
        ElMessage.error('移动失败！')
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    findFieldTypeAll() {
      myaxios.post("/dist/system/allEnum/getByTypeList", {ids: [3]}).then(rep => {
            if (rep.data.code !== 100) {
              ElMessage.error(rep.data.msg)
              return;
            }
            let data = rep.data.data;
            let val = {};
            if (!data) {
              return;
            }
            for (const item of data) {
              if (!item.children) {
                continue;
              }
              switch (item.id) {
                case 2:
                  val.restMethod = item.children;
                  break;
                case 3:
                  val.fieldType = item.children;
                  this.fieldTypeAll = item.children
                  val.fieldTypeMap = children.reduce((map, {enumValue, enumName}) => {
                    map[enumValue.toString()] = enumName;
                    return map;
                  }, {});
                  break;
                case 43:
                  val.paramType = item.children;
                  break;
                case 45:
                  val.paramDataType = item.children;
                  break;
                case 52:
                  val.descMode = item.children;
                  break;
              }
            }

            this.$store.dispatch("setAllEnum", val);
          },
          err => {
            ElMessage.error(err.response.data);
          }
      );
    }
  },
  mounted() {
    this.findAllField()
    this.findAllApiInfo()
    this.findFieldTypeAll()
  },
  watch: {
    filterFieldName() {
      this.filterByName()
    }
  }
}
</script>

<style scoped>
.el-table__header {
  margin-bottom: 0 !important;
}

table {
  margin-bottom: 0 !important;
}

.icon-button {
  margin: 0;
  padding: 6px;
}
</style>